package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.exception.leaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import io.netty.util.internal.StringUtil;
import kotlin.contracts.Returns;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private SystemUserMapper systemUserMapper;

    //获取图形验证码
    @Override
    public CaptchaVo getCheckCode() {
        //1.创建验证码对象
        SpecCaptcha specCaptcha = new SpecCaptcha(115,45,4);

        //2.获取验证码的文本内容
        String text = specCaptcha.text();
        //3.转换获取图片的地址
        String imageUrl = specCaptcha.toBase64();
        //4.生成key，唯一的
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String key = RedisConstant.ADMIN_LOGIN_PREFIX+uuid;

        //5.存储Redis，并设置过期时间
        stringRedisTemplate.opsForValue().set(key,text,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        //6.返回验证码对象  key是在redis中的key名，因为一会要校验，前端将验证码的key回传，去redis中查找，作比对
        CaptchaVo captchaVo = new CaptchaVo(imageUrl,key);
        return captchaVo;


    }

    //实现登录
    @Override
    public String login(LoginVo loginVo) {
        //获取前端发送的登录数据
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        String captchaKey = loginVo.getCaptchaKey();
        String captchaCode = loginVo.getCaptchaCode();
        //2.判断验证码
        //判断captchaCode是否为空
//        if(captchaCode==null){
//            throw new leaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);//验证码为空
//        }
        if(!StringUtils.hasText(captchaCode)){
            throw  new leaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);//未输入验证码
        }
        //3.通过验证码的key从redis中获取验证码的value，若key不存在，则代表验证码过期了
        String value = stringRedisTemplate.opsForValue().get(captchaKey);
        if(value==null){
            throw new leaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);//验证码已过期
        }
        //3.2验证码输入校验
        if(!captchaCode.equalsIgnoreCase(value)){
            throw new leaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);//验证码错误
        }
        //验证码验证之后，要在redis中删除
         stringRedisTemplate.delete(captchaKey);
        //4.根据用户名查询数据库
        SystemUser systemUser = systemUserMapper.selectOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername, username));
        if(systemUser==null){
            throw new leaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);//账号不存在
        }
        //5.查看用户状态,判断是否被禁用，0表示被禁用
        //baseStatus是枚举对象，所以要获得code
        if(systemUser.getStatus().getCode()==0){
            throw new leaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);//该用户被禁用
        }
        //6.校验密码
//        SystemUser systemUserPassword = systemUserMapper.selectOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getPassword, password));
        //用前端的明文加密和后端的密文作比较
        if(!DigestUtils.md5Hex(password).equals(systemUser.getPassword())){
            throw new leaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);//用户名或密码错误
        }
        //7.借助JWT工具生成Token
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());

        return token;
    }

    //获取登录用户的个人信息
    @Override
    public SystemUserInfoVo getSystemUserInfoVoById(Long userId) {
       //基于userId查询用户个人信息
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
